// Copyright (C) Kumo inc. and its affiliates.
// Author: Jeff.li lijippy@163.com
// All rights reserved.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//


#pragma once

#include <unordered_map>
#include <vector>
#include <pollux/dwio/dwrf/common/encryption_specification.h>

namespace kumo::pollux::dwrf::encryption {

template <typename T>
class EncryptionHandlerBase {
 public:
  EncryptionHandlerBase() = default;

  EncryptionHandlerBase(const EncryptionHandlerBase& handler)
      : providerType_(handler.providerType_),
        childNodes_{handler.childNodes_},
        rootNodes_{handler.rootNodes_} {
    providers_.reserve(handler.providers_.size());
    for (auto& provider : handler.providers_) {
      providers_.push_back(provider->clone());
    }
  }

  virtual ~EncryptionHandlerBase() = default;

  bool isEncrypted() const {
    return rootNodes_.size() > 0;
  }

  bool isEncrypted(uint32_t nodeId) const {
    return childNodes_.find(nodeId) != childNodes_.end();
  }

  dwio::common::encryption::EncryptionProvider getKeyProviderType() const {
    return providerType_;
  }

  uint32_t getEncryptionRoot(uint32_t nodeId) const {
    return childNodes_.at(nodeId);
  }

  uint32_t getEncryptionGroupCount() const {
    return providers_.size();
  }

  uint32_t getEncryptionGroupIndex(uint32_t nodeId) const {
    return rootNodes_.at(getEncryptionRoot(nodeId));
  }

  const T& getEncryptionProvider(uint32_t nodeId) const {
    return getEncryptionProviderByIndex(getEncryptionGroupIndex(nodeId));
  }

  const T& getEncryptionProviderByIndex(uint32_t groupIndex) const {
    return *providers_.at(groupIndex);
  }

 protected:
  dwio::common::encryption::EncryptionProvider providerType_;
  //  child nodes -> root nodes where encryption was applied
  melon::F14FastMap<uint32_t, uint32_t> childNodes_;
  // root nodes -> decrypter index
  melon::F14FastMap<uint32_t, uint32_t> rootNodes_;
  std::vector<std::unique_ptr<const T>> providers_;
};

} // namespace kumo::pollux::dwrf::encryption
